import Vue from 'vue'
import Vuex from 'vuex'
import { getRequest } from "../utils/api";
import '../utils/stomp'
import { Notification } from 'element-ui';

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
  state: sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {
    routes: [],
    sessions: {},             //聊天记录
    users: [],                //用户列表
    groups: [],               // 群组列表
    online_uids: [],          // 在线用户的uid
    currentUser: null,        //当前登录用户
    currentGroup: null,       //当前群组
    currentSession: { username: '群聊', nickname: '群聊' },//当前选中的用户，默认为群聊
    currentList: '群聊',      //当前聊天窗口列表
    filterKey: '',
    ws: null,                 // socket 实例
    isDot: {},                //两用户之间是否有未读信息
    errorImgUrl: "http://127.0.0.1:8000/media/avatar/狗崽子.jpg",//错误提示图片
    shotHistory: {}           //拍一拍的记录历史
  },
  // 通过 mutations 来修改state中的全局数据
  mutations: {
    // state 就是上文中定义的 state 
    initRoutes(state, data) {
      state.routes = data;
    },
    changeCurrentSession(state, currentSession) {
      //切换到当前用户就标识消息已读
      Vue.set(state.isDot, state.currentUser.username + "#" + currentSession.username, false);
      //更新当前选中的用户
      state.currentSession = currentSession;
    },
    changeCurrentGroup(state, group) {
      state.currentGroup = group
    },
    //修改当前聊天窗口列表
    changeCurrentList(state, currentList) {
      state.currentList = currentList;
    },
    //保存群聊消息记录
    addGroupMessage(state, msg) {
      console.log("group msg: ", msg)
      let groupId = msg.groupId
      let message = state.sessions[groupId]
      if (!message) {
        //state.sessions[state.currentHr.username+"#"+msg.to]=[];
        Vue.set(state.sessions, groupId, []);
      }
      state.sessions[groupId].push({
        fromUid: msg.fromUid,
        groupId: msg.groupId,
        fromNickname: msg.fromNickname,
        avatar: msg.avatar,
        content: msg.content,
        messageTypeId: msg.messageTypeId,
        createTime: new Date(),
      })
    },
    //保存单聊数据
    addMessage(state, msg) {
      let to_uid = msg.to_uid                // 21   12
      let from_uid = msg.from_uid            // 12   21
      let chat_id = ""
      if (to_uid > from_uid) {
        chat_id = to_uid + "#" + from_uid    // 21#12
      } else {
        chat_id = from_uid + "#" + to_uid    // 21#12
      }
      let message = state.sessions[chat_id]
      if (!message) {
        //创建保存消息记录的数组
        Vue.set(state.sessions, chat_id, []);
      }
      state.sessions[chat_id].push({
        content: msg.content,
        date: new Date(),
        fromNickname: msg.from_nickname,
        fromAvatar: msg.from_avatar,
        messageTypeId: msg.messageTypeId,
        self: !msg.notSelf
      })
    },
    /**
     *  获取本地聊天记录，同步数据库的记录保存到localStorage中。
     *  不刷新情况下都是读取保存再localStorage中的记录
     * @param state
     * @constructor
     */
    INIT_DATA(state, params) {
      //同步数据库中的群聊数据
      getRequest("/api/v1/group-message").then(resp => {
        // 获取数据库中存储的群聊信息
        if (resp) {
          Vue.set(state.sessions, '群聊', resp);
        }
      })
    },
    //保存系统所有用户
    INIT_USER(state, data) {
      state.users = data;
    },
    //请求并保存所有系统用户
    GET_USERS(state) {
      getRequest("/api/v1/chat/users").then(resp => {
        if (resp.code == 1) {
          state.users = resp.result;
        }
      })
    },
    // 获取群组信息
    GET_GROUPS(state, params) {
      getRequest(`/api/v1/group?uid=${params}`).then(resp => {
        if (resp.code == 1) {
          state.groups = resp.result;
        }
      })
    },
    // 获取在线用户
    get_online_uids(state, data) {
      state.online_uids = data
    }
  },

  actions: {
    // 初始化数据
    initData(context) {
      // 获取群组信息
      context.commit('GET_GROUPS', context.state.currentUser.uid)
      //初始化群聊记录
      // context.commit('INIT_DATA', context.state.currentUser.uid)
      //获取用户列表
      context.commit('GET_USERS')
    },
    // websocket
    connect(context) {
      // 获取到当前登录用户的uid
      var uid = context.state.currentUser.uid
      // 建立websocket连接
      context.state.ws = new WebSocket(`ws://127.0.0.1:8000/?uid=${uid}`);
      context.state.ws.onopen = () => {
        console.log("------ 建立连接成功 ------")
      };
      context.state.ws.onmessage = (msg) => {
        let receiveMsg = JSON.parse(msg.data);
        if (receiveMsg.messageTypeId == 1) {
          // 系统消息通知
          let online_uids = receiveMsg.online_uids
          context.commit('get_online_uids', online_uids)

        } else if (receiveMsg.messageTypeId == 2) {
          // 群聊消息
          receiveMsg.notSelf = true;
          context.commit('addGroupMessage', receiveMsg);

        } else if (receiveMsg.messageTypeId == 3) {
          // 私聊消息
          receiveMsg.notSelf = true;                  // 消息不是本人所发送的
          context.commit('addMessage', receiveMsg);   // 新增消息

        } else {
          // 机器人消息

        }
      };

      context.state.ws.onclose = (msg) => {
        console.log("关闭socket连接的msg: ", msg);
      }

    },
    //与Websocket服务端断开连接
    disconnect(context) {
      if (context.state.ws != null) {
        context.state.ws.close();
        console.log("------ 关闭连接成功 bye~ ------")
      }
    }
  }
})


store.watch(function (state) {
  return state.sessions
}, function (val) {
  console.log('CHANGE: ', val);
  localStorage.setItem('chat-session', JSON.stringify(val));
}, {
  deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;
